﻿using House.Common;
using House.DTO;
using House.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace House.Admin
{
    /*
    AuthorizeAttribute
    [AuthorizeAttribute]   [Authoriz] 验证用户信息  只允许登陆后的用户访问
     [AllowAnonymous] 所有用户都可以访问
     */
    public class PermissionAuthorize:AuthorizeAttribute
    {
        public string Permission { get; private set; }


        public PermissionAuthorize(string permission)
        {
            Permission = permission;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            /*
             1.获取用户信息
             2.获取用户的权限列表
             3.判断权限列表内包不包含指定的权限
             4.
              */
            var principal = filterContext.HttpContext.User as MyFormsPrincipal<LoginAdminDTO>;
            var user = principal.UserData;
            var service = DependencyResolver.Current.GetService<IPermission>();
            var permisssions = service.GetPermissionByUserId(user.Id);
            if (!permisssions.Contains(Permission))
            {
                //查询页面  操作页面
                if (filterContext.HttpContext.Request.IsAjaxRequest())//判断该请求是否是ajax操作
                {
                    filterContext.Result = new JsonResult() { Data = AjaxResult<bool>.Fail($"{user.Name}没有获取{Permission}权限") };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = $"{user.Name}没有{Permission}权限" };
                }
            }

            //base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }

    }
}